﻿using System;
using System.Collections.Generic;
using Koonsoft.HYCRM.DAL;
using Koonsoft.HYCRM.Model;
using Koonsoft.HYCRM.Model.Enum;
using log4net;
using System.Linq;

namespace Koonsoft.HYCRM.BLL
{
    public class EmpolyeeBLL
    {
        private ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private EmpolyeeDAL _dal = null;

        protected EmpolyeeDAL DAL
        {
            get
            {
                if (_dal == null)
                {
                    _dal = new EmpolyeeDAL();
                }

                return _dal;
            }
        }

        /// <summary>
        /// 根据员工ID获取员工姓名
        /// </summary>
        /// <param name="empolyeeID"></param>
        /// <returns></returns>
        public string GetEmpolyeeNameByEmpolyeeID(int empolyeeID)
        {
            return DAL.GetEmpolyeeNameByEmpolyeeID(empolyeeID);
        }

        /// <summary>
        /// 根据登录名获取员工信息
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public EmpolyeeInfo GetEmpolyeeInfoByLoginName(string loginName)
        {
            return DAL.GetEmpolyeeInfoByLoginName(loginName);
        }

        /// <summary>
        /// 获取用户是否过期
        /// </summary>
        /// <param name="loginName"></param>
        public bool IsUserExpired(string loginName)
        {
            return DAL.IsUserExpired(loginName);
        }

        /// <summary>
        /// 获取用户是否过期
        /// </summary>
        /// <param name="empolyeeID"></param>
        public bool IsUserExpired(int empolyeeID)
        {
            return DAL.IsUserExpired(empolyeeID);
        }

        /// <summary>
        /// 新增员工
        /// </summary>
        /// <param name="name"></param>
        /// <param name="loginName"></param>
        /// <param name="password"></param>
        /// <param name="creator"></param>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public bool AddNewEmpolyee(string name, string loginName, string password, string creator, string barcode)
        {
            return DAL.AddNewEmpolyee(name, loginName, password, creator, barcode);
        }


        /// <summary>
        /// 新增员工
        /// </summary>
        /// <returns></returns>
        public bool AddNewEmpolyee(EmpolyeeInfo empolyee)
        {
            return DAL.AddNewEmpolyee(empolyee);
        }


        /// <summary>
        /// 新增员工
        /// </summary>
        /// <returns></returns>
        public bool UpdateEmpolyee(EmpolyeeInfo empolyee)
        {
            return DAL.UpdateEmpolyee(empolyee);
        }

        /// <summary>
        /// 员工登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="otpcode"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Login(string username, string password, string otpcode, out string msg)
        {
            msg = string.Empty;

            #region 检查账号密码是否未填写)

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                msg = "用户名或密码不能为空";

                return false;
            }

            #endregion

            #region 检查用户密码是否正确

            if (!new EmpolyeeDAL().CheckEmpolyeeExist(username, password))
            {
                msg = "用户名密码不正确";

                return false;
            }

            #endregion

            #region 检查令牌密码是否正确

            var empolyee = new EmpolyeeBLL().GetEmpolyeeInfoByLoginName(username);

            if (empolyee != null)
            {
                if (!string.IsNullOrEmpty(empolyee.Barcode) && empolyee.Barcode.Length == 13)
                {
                    if (!OTPHelper.Verify(otpcode, empolyee.Barcode))
                    {
                        msg = "令牌码不正确";

                        return false;
                    }
                }
            }

            #endregion

            #region 检查用户状态

            #region 检查用户是否合同过期

            #endregion

            #endregion

            if (empolyee != null)
            {
                new EmpolyeeDAL().CreateLoginLog(empolyee.LoginName, empolyee.Status);
            }

            logger.Info(string.Format("用户{0}登录成功", username));

            return true;
        }

        public bool UpdateStatus(int id, int status)
        {
            return DAL.UpdateStatus(id, status);
        }

        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Cancel(int id)
        {
            return UpdateStatus(id, (int)EmpolyeeStatus.Cancel);
        }


        /// <summary>
        /// 获取员工所属分行编号列表
        /// </summary>
        /// <param name="empolyeeID"></param>
        /// <returns></returns>
        public List<int> GetBranchesByEmpolyeeID(int empolyeeID)
        {
            return DAL.GetBranchesByEmpolyeeID(empolyeeID);
        }

        /// <summary>
        /// 更新员工信息
        /// </summary>
        /// <param name="empolyeeName"></param>
        /// <param name="empolyeLoginName"></param>
        /// <param name="empolyeeID"></param>
        /// <param name="admin"></param>
        /// <param name="barcode"></param>
        /// <param name="entryTime"></param>
        /// <param name="roleid"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public void UpdateEmpolyeeInfoByEmpolyeeID(string empolyeeName, string empolyeLoginName, string admin, string barcode, int empolyeeID, DateTime entryTime
                                                        , int roleid, List<int> list)
        {
            DAL.UpdateEmpolyeeInfoByEmpolyeeID(empolyeeName, empolyeLoginName, admin, barcode, empolyeeID, entryTime);

            DAL.UpdateEmpolyeeRole(empolyeeID, roleid);

            EmpolyeeDAL.RemoveBranchRelation(empolyeeID);

            foreach (int item in list)
            {
                EmpolyeeDAL.AddBranchRelation(empolyeeID, item);
            }

            DAL.CancelEmplyeeContracts(empolyeeID);


            EmpolyeeInfo info = DAL.GetEmpolyeeInfoByEmpolyeeID(empolyeeID);
            if (info.Status == (int)EmpolyeeStatus.Create || info.Status == (int)EmpolyeeStatus.ContractExpires)
                UpdateStatus(empolyeeID, (int)EmpolyeeStatus.WaitSigning);
        }

        /// <summary>
        /// 合同签署
        /// </summary>
        /// <param name="empolyeeID"></param>
        /// <param name="contractId"></param>
        /// <param name="wordDocument"></param>
        /// <param name="wordName"></param>
        /// <param name="pdfName"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public bool CreateContract(int empolyeeID, string contractId, string wordDocument, string wordName, string pdfName, DateTime startTime, DateTime endTime)
        {
            {

                EmpolyeeInfo info = DAL.GetEmpolyeeInfoByEmpolyeeID(empolyeeID);
                info.Expansion = DAL.GetEmpolyeeExpansionByEmpolyeeID(empolyeeID);

                WordHelper word = new WordHelper();
                word.CreateNewWordDocument(wordDocument);

                word.Replace("合同开始日期", startTime.ToString("yyyy年MM月dd日"));
                word.Replace("合同终止日期", endTime.ToString("yyyy年MM月dd日"));
                word.Replace("地址1", info.Expansion.Address);
                word.Replace("地址2", info.Expansion.Address);
                word.Replace("地址3", info.Expansion.Address);
                word.Replace("用户名1", info.Name);
                word.Replace("用户名2", info.Name);
                word.Replace("用户名3", info.Name);
                word.Replace("用户名4", info.Name);
                word.Replace("用户名5", info.Name);
                word.Replace("用户名6", info.Name);
                word.Replace("签署日期", DateTime.Now.ToString("yyyy年MM月dd日"));
                word.Replace("签署日期2", DateTime.Now.ToString("yyyy年MM月dd日"));
                word.Replace("签署日期3", DateTime.Now.ToString("yyyy年MM月dd日"));
                word.Replace("签署日期4", DateTime.Now.ToString("yyyy年MM月dd日"));
                word.Replace("签署日期5", DateTime.Now.ToString("yyyy年MM月dd日"));
                word.Replace("签署日期6", DateTime.Now.ToString("yyyy年MM月dd日"));
                word.Replace("联系电话1", info.Expansion.Phone);
                word.Replace("联系电话2", info.Expansion.Phone);
                word.Replace("联系电话3", info.Expansion.Phone);
                word.Replace("身份证号1", info.Expansion.IdCard);
                word.Replace("身份证号2", info.Expansion.IdCard);
                word.Replace("身份证号3", info.Expansion.IdCard);
                word.Replace("身份证号4", info.Expansion.IdCard);

                word.SaveAs(wordName);
                word.Close();

                return new DOCToPDFHelper().DOCConvertToPDF(wordName, pdfName);
            }

        }

        /// <summary>
        /// 通过工号获取员工信息
        /// </summary>
        /// <param name="empolyeeID"></param>
        /// <returns></returns>
        public EmpolyeeInfo GetEmpolyeeInfoByEmpolyeeID(int empolyeeID)
        {
            EmpolyeeInfo info = DAL.GetEmpolyeeInfoByEmpolyeeID(empolyeeID);
            info.Expansion = DAL.GetEmpolyeeExpansionByEmpolyeeID(empolyeeID);

            return info;
        }

        /// <summary>
        /// 通过工号获取合同信息
        /// </summary>
        /// <param name="emplyeeId"></param>
        /// <returns></returns>
        public List<EmplyeeContract> GetEmplyeeContractByEmplyeeId(int emplyeeId)
        {
            return DAL.GetEmplyeeContractByEmplyeeId(emplyeeId);
        }

        /// <summary>
        /// 确认员工合同
        /// </summary>
        /// <param name="empolyeeID"></param>
        /// <returns></returns>
        public bool ConfirmEmplyeeContract(int empolyeeID)
        {
            DAL.ConfirmEmplyeeContract(empolyeeID);
            UpdateStatus(empolyeeID, (int)EmpolyeeStatus.Using);
            return true;
        }

        /// <summary>
        /// 确认员工合同
        /// </summary>
        /// <param name="empolyeeID"></param>
        /// <param name="validity"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool ConfirmEmplyeeContract(int empolyeeID, int validity, string filePath)
        {
            //try
            //{
                string contractId = string.Format("I{0}", DateTime.Now.ToString("yyMMddHHmmss"));
                string wordDocument = string.Format("{0}\\合同.doc", filePath);
                string wordPath = string.Format("{0}\\word\\{1}.doc", filePath, contractId);
                string pdfdbName = string.Format("{0}/Upload/pdf/{1}.pdf", "../..", contractId);
                string pdfPath = string.Format("{0}\\pdf\\{1}.pdf", filePath, contractId);

                var empolyee = new EmpolyeeBLL().GetEmpolyeeInfoByEmpolyeeID(empolyeeID);

                var contracts = new EmpolyeeBLL().GetEmplyeeContractByEmplyeeId(empolyeeID);

                DateTime startTime = empolyee.EntryTime;
                DateTime endTime = empolyee.EntryTime;

                if (contracts.Count(fun => fun.Status == 1 || fun.Status == 2) > 0)
                {
                    startTime = contracts.OrderByDescending(fun=>fun.EndTime).First().EndTime.Value;
                    endTime = contracts.OrderByDescending(fun => fun.EndTime).First().EndTime.Value;
                }

                if (validity <= 3)
                {
                    endTime = endTime.AddMonths(validity);
                }
                else
                {
                    if (startTime < DateTime.Now)
                    {
                        if (empolyee.EntryTime.AddYears(DateTime.Now.Year - empolyee.EntryTime.Year) < DateTime.Now)
                        {
                            startTime = empolyee.EntryTime.AddYears(DateTime.Now.Year - empolyee.EntryTime.Year);
                        }
                        else
                        {
                            startTime = empolyee.EntryTime.AddYears(DateTime.Now.Year - empolyee.EntryTime.Year - 1);
                        }
                    }
                    startTime = startTime.AddMonths(3);
                    endTime = startTime.AddMonths(validity);
                }

                CreateContract(empolyeeID, contractId, wordDocument, wordPath, pdfPath, startTime, endTime);
                DAL.AddEmplyeeContracts(empolyeeID, pdfdbName, contractId, startTime, endTime);
            //}
            //catch (Exception ex)
            //{
            //    logger.Error("确认合同异常", ex);
            //}

            UpdateStatus(empolyeeID, (int)EmpolyeeStatus.Using);

            return true;
        }

        /// <summary>
        /// 更新用户角色
        /// </summary>
        /// <param name="empolyeeID"></param>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public bool UpdateEmpolyeeRole(int empolyeeID, int roleID)
        {
            return DAL.UpdateEmpolyeeRole(empolyeeID, roleID);
        }


        /// <summary>
        /// 根据生日计算年龄
        /// </summary>
        /// <param name="birthDate"></param>
        /// <param name="inceptionDate"></param>
        /// <returns></returns>
        public static int CalculateAge(DateTime birthDate, DateTime inceptionDate)
        {
            // cache the current time       
            // get the difference in years
            int years = inceptionDate.Year - birthDate.Year;

            // subtract another year if we're before the
            // birth day in the current year
            if (inceptionDate.Month < birthDate.Month || (inceptionDate.Month == birthDate.Month && inceptionDate.Day < birthDate.Day)) //如果需要考虑2.29日的情况请自己修改判断条件
                --years;

            return years;
        }
    }
}
